class WebSocketClass {
    constructor(url = 'ws://' + location.host + process.env.VUE_APP_SIDDHI_WS_API +'/console', webSocketError = 0, callback = () => { }) {
        this.instance = null;
        this.status = 'close'
        this.callback = callback; // 回调函数
        this.wsurl = url; // ws路径
        this.webSocketError = webSocketError // 初始化重连次数
        this.webSocketErrorMax = 10 // 最大的重连次数
        this.socketInit(url);
    }
    static getInstance() {
        if (!this.instance) {
            this.instance = new WebSocketClass(this.wsurl, this.webSocketError, this.callback);
        }
        return this.instance;
    }
    // 初始化socke
    socketInit(url) {
        if (url != undefined) {
            this.ws = new WebSocket(url);
            if (this.status == 'close') {
                this.ws.onopen = e => {
                    this.status = 'open';
                    console.log(`连接成功`, e);
                    this.getMessage();
                };
            }
            if (this.status == 'open') {
                this.ws.onclose = msg => {
                    console.log(msg, 'oncloseonclose');
                    // 重连
                    if (this.webSocketError < this.webSocketErrorMax) {
                        setTimeout(() => {
                            this.socketInit(this.wsurl)
                        }, 500)
                    } else {
                        console.log('组件销毁或者重连数次过多');
                    }
                }
            }

            this.ws.onerror = err => {
                this.webSocketError++
                console.log(err, 'onerroronerror');
            }
        }
    }
    // 接受消息
    getMessage() {
        this.ws.onmessage = e => {
            var loggerObj = JSON.parse(e.data);
            var type = "";
            var colorDIffType = "";
            if (loggerObj.level == "INFO" || loggerObj.level == "WARN") {
                type = "INFO";
                colorDIffType = "INFO-LOGGER";
            } else if (loggerObj.level == "ERROR") {
                type = "ERROR";
                colorDIffType = "ERROR";
            }
            var stacktrace = "";
            if (loggerObj.stacktrace != null) {
                stacktrace = "<pre>" + loggerObj.stacktrace + "</pre>";
            }
            var logMessage =
                "[" +
                loggerObj.timeStamp +
                "] " +
                type +
                " " +
                "{" +
                loggerObj.fqcn +
                "} - " +
                loggerObj.message +
                " " +
                stacktrace;
            var message = {
                type: colorDIffType,
                message: logMessage,
            };
            this.callback(message)
        }
    }
    // 手动关闭socket
    close() {
        this.ws.close();
        // this.ws.send('close');
        this.webSocketError = 89
        this.status = 'close';
    }
}
export default WebSocketClass;